import React, { Component, Fragment } from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import router from 'umi/router';
import _ from 'lodash';

import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Card,
  Row,
  Col,
  Input,
  Select,
  Checkbox,
  Button,
  message,
  Upload,
  Modal,
} from 'antd';
import { PlusOutlined, EyeInvisibleOutlined } from '@ant-design/icons';

import '@ant-design/compatible/assets/index.css';

const { Option } = Select;
const { Item } = Form;
interface CouriersSaveProps extends FormComponentProps {
  dispatch: Dispatch;
  detailInfo: any;
  userInfo: any;
  INITINFO: any;
  location: {
    query: {
      userId?: number;
      courierId?: number;
    };
  };
}

interface CouriersSaveState {
  isData: boolean;
  staffType: number;
  positionList: any;
  img1: string;
  img2: string;
  img1Obj: any;
  img2Obj: any;
  visibleImg1: boolean;
  visibleImg2: boolean;
}

@connect(
  ({
    couriersMangagementSaveOrUpdate: { detailInfo, userInfo },
    common: { INITINFO },
  }: any) => ({
    detailInfo,
    userInfo,
    INITINFO,
  }),
)
class CouriersSaveElem extends Component<CouriersSaveProps, CouriersSaveState> {
  state: CouriersSaveState = {
    isData: true,
    staffType: 1,
    positionList: [],
    img1: '',
    img2: '',
    img1Obj: {},
    img2Obj: {},
    visibleImg1: false,
    visibleImg2: false,
  };

  static getDerivedStateFromProps(nextProps: any, preState: any) {
    const { detailInfo = {} } = nextProps;
    const { positionList = '' } = detailInfo;
    const { isData } = preState;
    const new_positionList = positionList.split(',').map((item: string) => Number(item));
    if (detailInfo.userId && isData) {
      return {
        isData: false,
        staffType: detailInfo.staffType,
        img1: detailInfo.idcardFrontUrl,
        img2: detailInfo.idcardBackUrl,
        positionList: new_positionList,
      };
    }
    return null;
  }

  componentDidMount() {
    const { location: { query } } = this.props;
    if (Object.keys(query).length > 0) this.fetchDetailInfo(query);

    this.fetchAction('common/fetchLogisList');
  }

  componentDidUpdate(props: any) {
    const { location: { query } } = this.props;
    if (Object.keys(query).length > 0 && !_.isEqual(query, props.location.query)) {
      this.fetchDetailInfo(query);
    }
  }

  componentWillUnmount() {
    this.fetchAction('clear');
  }

  fetchDetailInfo = (query: any) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'couriersMangagementSaveOrUpdate/fetch',
      payload: query,
    });
  };

  handleVerPhone = (e: any) => {
    // 验证手机号并返回用户信息
    const { value } = e.target;
    this.fetchAction('verPhone', { phone: value });
  };

  /** 更改员工类型 */
  handleChangeStaff = (staffType: number) => {
    const { form: { resetFields } } = this.props;
    this.setState({ staffType, positionList: [] }, () => resetFields(['positionList']));
  };

  /** 选择岗位性质 */
  handleChangePosition = (positionList: any) => this.setState({ positionList });

  fetchAction = (typeName: string, payload: any = {}) => {
    const { dispatch } = this.props;
    const type = typeName.indexOf('common') >= 0
      ? typeName : `couriersMangagementSaveOrUpdate/${typeName}`;
    dispatch({ type, payload });
  };

  getBase64 = (img: any, callback: any) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  }

  handleUpload = (name: string, { file, fileList }: any) => {
    this.getBase64(file.originFileObj, (imageUrl: string) => {
      if (name === 'img1') {
        this.setState({
          img1: imageUrl,
          img1Obj: fileList.length <= 0 ? 1 : file.originFileObj,
        });
      }

      if (name === 'img2') {
        this.setState({
          img2: imageUrl,
          img2Obj: fileList.length <= 0 ? 1 : file.originFileObj,
        });
      }
    });
  }

  showImage = (name: string) => {
    if (name === 'img1') {
      this.setState({ visibleImg1: true });
    }
    if (name === 'img2') {
      this.setState({ visibleImg2: true });
    }
  }

  hideImage = () => {
    this.setState({
      visibleImg1: false,
      visibleImg2: false,
    });
  }

  handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();

    const { form: { validateFieldsAndScroll } } = this.props;
    validateFieldsAndScroll((errors, { agin_password, ...values }) => {
      if (errors) return;

      if (values.password !== agin_password) {
        message.error('两次密码输入不一致');
      } else {
        const phoneVer = /^1[3456789]\d{9}$/;
        if (!phoneVer.test(values.phone)) {
          message.error('手机号格式不正确');
          return;
        }

        const { positionList } = this.state;
        const params = {
          ...values,
          positionList: positionList.join(','),
        };

        const { location: { query: { userId, courierId } }, detailInfo } = this.props;
        if (userId && courierId) {
          params.userId = userId;
          params.courierId = courierId;
        }

        const { img1Obj, img2Obj } = this.state;
        if (Object.keys(img1Obj).length) {
          params.idcardFrontImg = img1Obj;
        } else {
          params.idcardFrontUrl = detailInfo.idcardFrontUrl;
        }

        if (Object.keys(img2Obj).length) {
          params.idcardBackImg = img2Obj;
        } else {
          params.idcardBackUrl = detailInfo.idcardBackUrl;
        }

        delete params.img1;
        delete params.img2;

        this.fetchAction('saveOrUpdate', params);
      }
    });
  };

  render() {
    const {
      staffType,
      positionList,
      img1,
      img2,
      visibleImg1,
      visibleImg2,
    } = this.state;

    const {
      form: { getFieldDecorator },
      detailInfo,
      userInfo,
      location: { query },
      INITINFO: { logisList },
    } = this.props;

    const uploadButton = (
      <div>
        <PlusOutlined />
        <div className="ant-upload-text">上传</div>
      </div>
    );

    return (
      <Fragment>
        <PageHeader />

        <Card bordered={false}>
          <Form
            hideRequiredMark
            className="tableListForm"
            onSubmit={this.handleSubmit}
          >
            <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
              <Col md={8} sm={24}>
                <Item label=" 物 流 中 心 ">
                  {getFieldDecorator('logisId', {
                    initialValue: detailInfo.logisId,
                    rules: [{ required: true, message: '请选择物流中心' }],
                  })(
                    <Select
                      showSearch
                      placeholder="请选择"
                      filterOption={(input: any, option: any) => (
                        option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                      )}
                    >
                      {logisList.map((item: any) => (
                        <Option value={item.id} key={item.id}>{item.name}</Option>
                      ))}
                    </Select>,
                  )}
                </Item>
              </Col>
            </Row>
            <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
              <Col md={8} sm={24}>
                <Item label=" 员 工 类 型 ">
                  {getFieldDecorator('staffType', {
                    initialValue: detailInfo.staffType || 1,
                    rules: [{ required: true, message: '请选择员工类型' }],
                  })(
                    <Select placeholder="请选择" onChange={this.handleChangeStaff}>
                      <Option value={1}>内部员工</Option>
                      <Option value={2}>京东员工</Option>
                    </Select>,
                  )}
                </Item>
              </Col>
            </Row>
            <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
              <Col md={8} sm={24}>
                <Item label="登录手机号">
                  {getFieldDecorator('phone', {
                    initialValue: detailInfo.phone,
                    rules: [{ required: true, message: '请输入投递人手机' }],
                  })(
                    <Input
                      allowClear
                      type="number"
                      placeholder="请输入"
                      disabled={!!detailInfo.userId}
                      onBlur={this.handleVerPhone}
                    />,
                  )}
                </Item>
              </Col>
              {staffType !== 1 && (
                <Col md={8} sm={24}>
                  <span style={{ lineHeight: '32px' }}>乐加系统手机号</span>
                </Col>
              )}
            </Row>
            <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
              <Col md={8} sm={24}>
                <Item label=" 员 工 姓 名 ">
                  {getFieldDecorator('realName', {
                    initialValue: userInfo.realName || detailInfo.realName,
                    rules: [{ required: true, message: '请输入投递人姓名' }],
                  })(<Input allowClear placeholder="请输入" />)}
                </Item>
              </Col>
              {staffType !== 1 && (
                <Col md={8} sm={24}>
                  <span style={{ lineHeight: '32px' }}>乐加系统姓名</span>
                </Col>
              )}
            </Row>
            {staffType === 1 && (
              <Row gutter={{ md: 8, xl: 24, lg: 48 }} className="mobileT">
                <Col md={8} sm={24}>
                  <Item label="登录用户名">
                    {getFieldDecorator('name', {
                      initialValue: userInfo.name || detailInfo.name,
                      rules: [{ required: true, message: '请输入登陆用户名' }],
                    })(
                      <Input
                        allowClear
                        autoComplete="off"
                        disabled={!!(!query.userId && userInfo.id) || !!detailInfo.userId}
                        placeholder="请输入"
                      />,
                    )}
                  </Item>
                </Col>
              </Row>
            )}
            {staffType === 2 && (
              <Row gutter={{ md: 8, xl: 24, lg: 48 }} className="mobileT">
                <Col md={8} sm={24}>
                  <Item label=" 身 份 证 号 ">
                    {getFieldDecorator('idNumber', {
                      initialValue: detailInfo.idNumber,
                      rules: [{ required: true, message: '请输入身份证号码' }],
                    })(<Input allowClear placeholder="请输入" />)}
                  </Item>
                </Col>
                <Col md={8} sm={24}>
                  <span style={{ lineHeight: '32px' }}>乐加系统身份证号</span>
                </Col>
              </Row>
            )}
            {!query.userId && (
              <Fragment>
                <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
                  <Col md={8} sm={24}>
                    <Item label=" 设 置 密 码 ">
                      {getFieldDecorator('password', {
                        rules: [{ required: true, message: '请输入密码' }],
                      })(<Input
                        allowClear
                        autoComplete="off"
                        type="password"
                        placeholder="请输入"
                      />)}
                    </Item>
                  </Col>
                </Row>
                <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
                  <Col md={8} sm={24}>
                    <Item label=" 确 认 密 码 ">
                      {getFieldDecorator('agin_password', {
                        rules: [{ required: true, message: '请再次输入密码' }],
                      })(<Input allowClear type="password" placeholder="请输入" />)}
                    </Item>
                  </Col>
                </Row>
              </Fragment>
            )}
            {staffType === 1 && (
              <>
                <Row gutter={{ md: 8, xl: 24, lg: 48 }} className="mobileT">
                  <Col md={8} sm={24}>
                    <Item label=" 身 份 证 号 ">
                      {getFieldDecorator('idNumber', {
                        initialValue: detailInfo.idNumber,
                        rules: [
                          { required: true, message: '请输入身份证号码' },
                          { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '身份证格式不正确' },
                        ],
                      })(
                        <Input allowClear maxLength={18} placeholder="请输入" />,
                      )}
                    </Item>
                  </Col>
                </Row>
                <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
                  <Col md={12} sm={24}>
                    <Item label="身份证正面">
                      {getFieldDecorator('img1', {
                        initialValue: img1,
                        rules: [{ required: !img1, message: '请上传图片' }],
                      })(
                        <Upload
                          accept=".png,.jpg,.jpeg"
                          listType="picture-card"
                          className="uploadBtn"
                          style={{ position: 'relative' }}
                          showUploadList={false}
                          onChange={e => this.handleUpload('img1', e)}
                        >
                          {
                            img1
                              ? <img src={img1} alt="avatar" style={{ width: '100%' }} />
                              : uploadButton
                          }
                        </Upload>,
                      )}
                      <div style={{ color: '#3C94F8' }}>支持扩展名：png、jpg、jpeg</div>
                      {
                        img1 && (
                          <div style={{ position: 'absolute', top: 0, left: 70 }}>
                            <EyeInvisibleOutlined onClick={() => this.showImage('img1')} />
                          </div>
                        )
                      }
                    </Item>
                  </Col>
                </Row>
                <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
                  <Col md={12} sm={24}>
                    <Item label="身份证背面">
                      {getFieldDecorator('img2', {
                        initialValue: detailInfo.img2,
                        rules: [{ required: !img2, message: '请上传图片' }],
                      })(
                        <Upload
                          accept=".png,.jpg,.jpeg"
                          listType="picture-card"
                          className="uploadBtn"
                          style={{ position: 'relative' }}
                          showUploadList={false}
                          onChange={e => this.handleUpload('img2', e)}
                        >
                          {
                            img2
                              ? <img src={img2} alt="avatar" style={{ width: '100%' }} />
                              : uploadButton
                          }
                        </Upload>,
                      )}
                      <div style={{ color: '#3C94F8' }}>支持扩展名：png、jpg、jpeg</div>
                      {
                        img2 && (
                          <div style={{ position: 'absolute', top: 0, left: 70 }}>
                            <EyeInvisibleOutlined onClick={() => this.showImage('img2')} />
                          </div>
                        )
                      }
                    </Item>
                  </Col>
                </Row>
                <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
                  <Col md={12} sm={24}>
                    <Item label=" 岗 位 性 质 ">
                      {getFieldDecorator('positionList', {
                        initialValue: positionList,
                        rules: [{ required: true, message: '请选择岗位性质' }],
                      })(
                        <Checkbox.Group onChange={this.handleChangePosition}>
                          <Checkbox value={1}>投递人</Checkbox>
                          <Checkbox value={4}>盘点员</Checkbox>
                          <Checkbox value={8}>上门取件员</Checkbox>
                        </Checkbox.Group>,
                      )}
                    </Item>
                  </Col>
                </Row>
              </>
            )}
            <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
              <Col md={8} sm={24}>
                <Button
                  type="primary"
                  htmlType="submit"
                >
                  保存
                </Button>
                <Button
                  ghost
                  type="primary"
                  className="marginL16"
                  onClick={() => router.goBack()}
                >
                  取消
                </Button>
              </Col>
            </Row>
          </Form>
        </Card>

        <Modal
          title="图片展示"
          visible={visibleImg1 || visibleImg2}
          footer={null}
          onCancel={this.hideImage}
        >
          <img src={visibleImg1 ? img1 : img2} style={{ width: 464 }} alt="" />
        </Modal>
      </Fragment>
    );
  }
}

export default Form.create<CouriersSaveProps>()(CouriersSaveElem);
